package com.company.cloud.oss.modules.app.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.oss.modules.app.controller.req.OssCallbackSignParam;
import com.company.cloud.oss.modules.app.service.OssStoreService;
import com.company.common.server.config.id.OssIdUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.HttpContextUtils;
import com.company.cloud.common.utils.IpUtils;
import com.company.cloud.oss.config.OssConfig;
import com.company.cloud.oss.modules.base.entity.OssStoreInfo;
import com.company.cloud.oss.modules.base.service.OssStoreInfoService;
import com.company.cloud.oss.modules.cache.models.OssModel;
import com.company.cloud.oss.modules.cache.utils.OssConvertUtils;
import com.company.cloud.oss.utils.AliYunOssCallbackModel;
import com.company.cloud.oss.utils.AliYunOssUtils;

import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;

@Log4j2
@RestController
@RequestMapping("/app/oss")
@Api(tags="App_OSS_服务")
public class OssCallbackController {
	
	@Autowired
	private OssConfig ossConfig;
	@Autowired
	private OssStoreService ossStoreService;




	@PostMapping(value = "/callback",produces ="application/json")
	@ResponseBody
	public BaseResult callback(@RequestBody String body) {
		if(StringUtils.isEmpty(body)) {
			return BaseResult.error();
		}
		log.debug("+++++JS上传OSS回调结果:{}",body);
		//验证签名
		HttpServletRequest request=HttpContextUtils.getRequest();
		try {
			boolean ret=this.verifyOSSCallbackRequest(request, body);
			if(ret==false) {
				log.debug("+++++JS上传OSS回调验签失败");
			}
		} catch (NumberFormatException | IOException e) {
			log.debug("+++++JSJS上传OSS回调验签报错{}",e.getMessage());
			return BaseResult.error();
		}

		AliYunOssCallbackModel callbackModel=AliYunOssUtils.getCallbackModel(body);
		OssStoreInfo entity=ossStoreService.add(callbackModel);
		OssModel data= OssConvertUtils.getOssModel(entity);
		return BaseResult.ok(data);
	}

	@Deprecated
	@Login
	@GetMapping("/getAliyunOss")
	public BaseResult getAliyunOss() {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		Map<String, String> respMap = AliYunOssUtils.getOssSign(ossConfig,userInfo.getCompanyNo(),userInfo.getId(),null,0, BaseConstant.YNEnum.NO.getCode());
		HttpServletResponse response= HttpContextUtils.getResponse();
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST");
		return BaseResult.ok(respMap);
	}


	@Login
	@PostMapping("/getAliyunOssSign")
	public BaseResult getAliyunOssSign(@RequestBody OssCallbackSignParam params) {
		LoginSimpleUserInfo userInfo= AuthContextUtils.getUser();
		Map<String, String> respMap = AliYunOssUtils.getOssSign(ossConfig,userInfo.getCompanyNo(),userInfo.getId(),params.getResizeWidht(),params.getQuality(),params.getIsImg());
		HttpServletResponse response= HttpContextUtils.getResponse();
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "GET, POST");
		return BaseResult.ok(respMap);
	}

	/**
	 * 验证上传回调的Request
	 * @param request
	 * @param ossCallbackBody
	 * @return 
	 * @throws NumberFormatException
	 * @throws IOException
	 */
	protected boolean verifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody)
			throws NumberFormatException, IOException {
		boolean ret = false;
		String autorizationInput =request.getHeader("Authorization");
		String pubKeyInput = request.getHeader("x-oss-pub-key-url");
		byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
		byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
		String pubKeyAddr = new String(pubKey);
		if (!pubKeyAddr.startsWith("http://gosspublic.alicdn.com/")
				&& !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/")) {
			System.out.println("pub key addr must be oss addrss");
			return false;
		}
		String retString = executeGet(pubKeyAddr);
		retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
		retString = retString.replace("-----END PUBLIC KEY-----", "");
		String queryString = request.getQueryString();
		String uri = request.getRequestURI();
		String decodeUri = java.net.URLDecoder.decode(uri, "UTF-8");
		String authStr = decodeUri;
		if (queryString != null && !queryString.equals("")) {
			authStr += "?" + queryString;
		}
		authStr += "\n" + ossCallbackBody;
		ret = doCheck(authStr, authorization, retString);
		return ret;
	}
	
	/**
	 * 获取public key
	 * @param url
	 * @return
	 */
	@SuppressWarnings({ "finally" })
	private String executeGet(String url) {
		BufferedReader in = null;
		String content = null;
		try {
			// 定义HttpClient
			@SuppressWarnings("resource")
			DefaultHttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);

			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			content = sb.toString();
		} catch (Exception e) {
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return content;
		}
	}
	
	/**
	 * 验证RSA
	 * @param content
	 * @param sign
	 * @param publicKey
	 * @return
	 */
	public static boolean doCheck(String content, byte[] sign, String publicKey) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			byte[] encodedKey = BinaryUtil.fromBase64String(publicKey);
			PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
			java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
			signature.initVerify(pubKey);
			signature.update(content.getBytes());
			boolean bverify = signature.verify(sign);
			return bverify;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}
	
}
